<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <a-spin :spinning="loading[0] || loading[1] || (spinning && (editModel != 2 || detailsId ? true : false))">
      <!-- 预验收申请编辑 -->
      <a-form-model
        id="base-breadcrumb"
        style="position: relative"
        ref="ruleForm"
        :model="form"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        :rules="editModel != 0 ? rules : {}"
      >
        <!-- 项目信息 -->
        <!-- :is-need-auth="editModel == 2 ? true: false" -->
        <base-info 
          ref="baseInfo"
          :disabled="!!detailsId || editModel != 2 ? true : false"
          :form="form"
          :isNeedAuth="true"
          :editModel="detailsId ? '1' : editModel"
          @companychange="companychange"
        ></base-info>
        <!-- 表格 -->
        <a-card :bordered="false" style="margin-bottom: 50px">
          <title-name title="验收信息"></title-name>
          <!-- 表单信息 -->
          <custom-form
            ref="customForm"
            :selectOption.sync="selectOption"
            :formList="formList"
            :form="form"
            @loading="(name, e) => (spinning = e)"
            :editModel="onlyRead ? 'V' : ''"
            @updateSelect="handleUpdateSelect"
          ></custom-form>
          <!-- <a-row v-if="editModel != 0">
            <a-form-model
              v-for="(item, index) in form.preAcceptanceTeam"
              :key="item.id"
              ref="preAcceptanceTeam"
              :model="item"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 18 }"
              :rules="rules"
            >
              <a-col :xs="24" :sm="12" :md="8" :lg="8">
                <a-form-model-item :label="index == 0 ? '预验收小组成员及分工' : ' '" :colon="index == 0">
                  <a-row type="flex" justify="space-between" style="margin-top:-3px">
                    <span>
                      <span class="mr20">{{ item.name }}</span
                      >{{ item.jobTitle || '' }}
                    </span>
                    <a class="del_btn" @click.stop="form.preAcceptanceTeam.splice(index, 1)">移除</a>
                  </a-row>
                  <a-button
                    v-if="index == form.preAcceptanceTeam.length - 1"
                    type="primary"
                    icon="plus"
                    @click="visible = true"
                    >添加</a-button
                  >
                </a-form-model-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="8">
                <a-form-model-item label="分工" prop="laborWork">
                  <BaseInput :maxLength="30" v-model="item.laborWork"></BaseInput>
                </a-form-model-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="8">
                <a-form-model-item label="验收部位/内容" prop="acceptanceContent">
                  <BaseInput :maxLength="30" v-model="item.acceptanceContent"></BaseInput>
                </a-form-model-item>
              </a-col>
            </a-form-model>
            <a-col v-show="!form.preAcceptanceTeam || form.preAcceptanceTeam.length < 1" :span="24">
              <a-form-model-item label="预验收小组成员" prop="preAcceptanceTeam">
                <a-button type="primary" icon="plus" @click="visible = true">添加</a-button>
              </a-form-model-item>
            </a-col>
          </a-row> -->
          <a-row v-if="onlyRead">
            <a-col :span="24">
              <a-form-model-item label="预验收小组成员及分工">
                <a-row
                  :gutter="12"
                  class="text_name"
                  v-for="item in form.preAcceptanceTeam"
                  :key="item.id"
                  style="width: 900px"
                >
                  <a-col :span="3">
                    <ellipsis tooltip :length="10">{{ item.name }}</ellipsis>
                  </a-col>
                  <a-col :span="4"
                    ><ellipsis tooltip :length="16">{{ item.jobTitle }}</ellipsis></a-col
                  >
                  <a-col :span="8"
                    >小组分工：<ellipsis tooltip :length="25">{{ item.laborWork }}</ellipsis></a-col
                  >
                  <a-col :span="9"
                    >负责验收部位/内容：<ellipsis tooltip :length="25">{{ item.acceptanceContent }}</ellipsis>
                  </a-col>
                </a-row>
                <div class="text_name" v-if="form.preAcceptanceTeam.length < 1">暂无</div>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <a-form-model-item label="施工质量项目自评">
                <BaseTextarea v-if="!onlyRead" type="textarea" v-model="form.selfEval"></BaseTextarea>
                <div v-else class="text_name">
                  {{ form.selfEval || '暂无' }}
                </div>
              </a-form-model-item>
            </a-col>
            <a-col v-if="onlyRead" :span="24">
              <a-form-model-item label="分公司总工意见">
                <div class="text_name">
                  {{ form.opinionOfChiefEngineerOfBranch || '暂无' }}
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form-model>
    </a-spin>
    <!-- 页脚操作栏 -->
    <div
      v-if="!isFromAudit"
      class="btn_box page-btn-right-top"
    >
      <BasePrintButton
        v-if="onlyRead"
        :beforePrintFn="() => getPritContent('CSCEC8XN-EQ-B30607')"
        class="button_right"
      />
      <a-button
        :disabled="loading[0] || loading[1]"
        v-if="editModel == 1 && statusCode === '0'"
        type="danger"
        class="button_right"
        @click="handleRemove"
        >删除草稿</a-button
      >
      <a-button
        :loading="loading[0]"
        :disabled="loading[1]"
        v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 2 || editModel == 3"
        type="primary"
        class="button_right"
        @click="handleSubmit(0)"
        >{{ statusCode === '3' ? '保存' : '保存草稿' }}</a-button
      >
      <a-button
        :loading="loading[1]"
        :disabled="loading[0]"
        v-if="(editModel == 1 && (statusCode === '0' || statusCode === '3')) || editModel == 2 || editModel == 3"
        type="primary"
        class="button_right"
        @click="handleSubmit(1)"
        >提交</a-button
      >
      <a-button v-if="checkVisibleInDetail" type="primary" @click="handleActiveClose">关闭</a-button>
    </div>
    <div v-if="!isConsultation && isFromAudit" class="page-btn-right-top">
      <a-button
        v-check-visible-in-detail
        style="margin: 0 10px"
        @click="$close"
      >
        关闭
      </a-button>
    </div>
    <!-- 表单弹窗 -->
    <search-by-org ref="dialogEdit" :visible.sync="visible" headerTitle="选择人员" @confirm="submitForm" />
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import SearchByOrg from '@/components/businessComponents/SearchByOrg' // 选择人员
import SelectQualityReceivance from '@/components/Select/SelectQualityReceivance' // 质量验收计划
import { application } from '@/api/quality/unitProject' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BaseInfo from '@/components/businessComponents/BaseInfo' // 基础信息
import { Ellipsis } from '@/components' // 表格
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
import Selector from '@/components/Select/Selector' // 通用下拉框
export default {
  name:'a'+ Date.now(),
  extends: new BaseEditPage(),
  components: {
    BaseInfo,
    SearchByOrg,
    Ellipsis,
    BasePrintButton
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      spinning: false,
      detailsId: '', // 质量计划id
      visible: false, // 人员选择弹窗控件
      loading: { 0: false, 1: false }, // 按钮loding控件
      editModel: 0, // 操作类型:0 查看;1 编辑;2 新增
      id: '', // 业务id
      form: { checkAcceptanceTypeId: '', preAcceptanceTeam: [], acceptorName: '', detailsId: '' },
      selectOption: {}, // 质量验收计划选中对象
      statusCode: '', // 审批状态
      rules: {
        branchCompanyId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        detailsId: [{ required: true, message: '请选择验收内容', trigger: 'change' }],
        checkAcceptanceTypeId: [{ required: true, message: '请选择质量验收类型', trigger: 'change' }],
        quantity: [{ required: true, message: '请输入数量', trigger: 'change' }],
        buildNumFloor: [{ required: true, whitespace: true, message: '请输入部位', trigger: 'change' }],
        acceptanceDate: [{ required: true, message: '请选择预验收时间', trigger: 'change' }],
        preAcceptanceTeam: [{ type: 'array', required: true, message: '请添加预验收小组成员', trigger: 'change' }],
        laborWork: [{ required: true, whitespace: true, message: '请输入分工', trigger: 'change' }],
        acceptanceContent: [{ required: true, whitespace: true, message: '请输入验收部位/内容', trigger: 'change' }],
      },
      isFromAudit: false, // 是否来自审批
       //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  computed: {
    // 只读模式
    onlyRead() {
      return this.editModel == 0 || !!this.businessId
    },
    // 表单列表
    formList() {
      return [
        this.editModel === 2 ? {
          label: '质量验收类型',
          type: Selector,
          keyName: 'checkAcceptanceTypeId',
          viewName: 'checkAcceptanceTypeName',
          attrs: {
            selectType: '23',
            labelInValue: false,
            filterFn: (item) => item.code === '0' || item.code === '2' || item.code === '3'
          },
        }: {
          keyName: 'checkAcceptanceTypeName',
          type: 'a-input',
          disabled: true,
          label: '质量验收类型',
        },
        this.editModel === 2 ? {
          type: SelectQualityReceivance,
          keyName: 'detailsId',
          viewName: 'detailsName',
          label: '验收内容',
          attrs: {
            ref: 'plan',
            checkAcceptanceTypeId: this.form.checkAcceptanceTypeId,
            projectId: this.form.projectId,
            isClear: !this.detailsId,
            isEdit: this.detailsId ? true : false,
          },
        } : {
          keyName: 'detailsName',
          type: 'a-input',
          disabled: true,
          label: '验收内容',
        },
        {
          keyName: 'quantity',
          type: 'a-input-number',
          label: '数量',
          precision: 0,
          attrs: {
            min: 0,
            max: 10000000,
          },
        },
        {
          keyName: 'buildNumFloor',
          type: 'a-input',
          label: '部位',
        },
        {
          keyName: 'acceptorName',
          disabled: true,
          placeholder: '请先选择质量验收计划',
          type: 'a-input',
          label: '验收负责人',
        },
        {
          keyName: 'acceptanceDate',
          type: 'a-date-picker',
          label: '预验收时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              return current && current < this.moment().startOf('day')
            },
          },
        },
      ]
    },
  },
  watch: {
    selectOption(e) {
      if (this.editModel == 2) {
        if (e && Object.keys(e)?.length > 0) {
          // 映射单位工程名称和验收负责人
          this.form.acceptorName = e.acceptorName
        } else {
          this.form.acceptorName = ''
        }
      }
    },
  },
 async created() {
    this.isFromAudit = !!this.$route.query.businessId
    this.$route.meta.title = ['预验收申请查看', '预验收申请编辑', '预验收申请添加'][
      this.editModel
    ]
    // 若不为添加操作，则请求详情
     if (this.editModel == 3) {
        this.projectId && this.$set(this.form, 'projectId', this.projectId)
        this.branchCompanyId && this.$set(this.form, 'branchCompanyId', this.branchCompanyId)
        this.checkAcceptanceTypeId && this.$set(this.form, 'checkAcceptanceTypeId', this.checkAcceptanceTypeId)
        this.checkAcceptanceTypeName && this.$set(this.form, 'checkAcceptanceTypeName', this.checkAcceptanceTypeName)
        this.detailsId && this.$set(this.form, 'detailsId', this.detailsId)
        this.detailsName && this.$set(this.form, 'detailsName', this.detailsName)
        this.acceptorName && this.$set(this.form, 'acceptorName', this.acceptorName)
     } else if (this.editModel != 2) {
      this.loading[0] = true
      application
        .getDetail({ id: this.id })
        .then((res) => {
          this.loading[0] = false
          this.form = res.data
          if(!this.form.preAcceptanceTeam) {
            this.form.preAcceptanceTeam = []
          }
          this.statusCode = res.data.statusCode
        })
        .catch((res) => {
          this.loading[0] = false
        })
    } else { 
      this.branchCompanyId && this.$set(this.form, 'branchCompanyId', this.branchCompanyId)
      this.projectId && this.$set(this.form, 'projectId', this.projectId)
      this.detailsId && this.$set(this.form, 'detailsId', this.detailsId)
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('quality_unitengpre_acceptance')
  },
  methods: {
    companychange(branchCompanyId) {
      console.log('branchCompanyIdbranchCompanyIdbranchCompanyId',branchCompanyId)
      this.form.branchCompanyId = branchCompanyId
    },
    /**
     * 更新质量验收计划的选中值
     * @param {String} key -事件标识
     * @param {Object} data -更新值
     */
    handleUpdateSelect(key, data) {
      if(key !== 'detailsId') return
      this.selectOption = data
    },
    /**
     * 选择预验收人员
     */
    submitForm(e) {
      if (this.form.preAcceptanceTeam?.some((item) => item.id === e.id)) {
        this.$message.warning('此人员已添加')
      } else {
        this.form.preAcceptanceTeam.push(e)
        this.$message.success('添加成功，请输入分工和验收部分')
        this.visible = false
      }
    },
    /**
     * 删除草稿
     */
    handleRemove() {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除草稿？',
        onOk: () => {
          return application.remove({ id: this.id }).then((res) => {
            this.$message.success('删除成功！')
            // 关闭当前页
            this.$multiTab.close()
          })
          // .catch((res) => {
          //   this.$message.warning('删除失败！')
          // })
        },
      })
    },
    /**
     * 提交表单
     */
    handleSubmit(statusCode) {
      this.setProcessConfig = null;
      let name = ['update', 'create'][this.id ? 0: 1] // 根据操作切换url地址
      this.$refs.ruleForm.validate((e) => {
        if (e || statusCode === 0) {
          let result = true
          statusCode === 0 && this.$refs.ruleForm.clearValidate()
          // 校验预验收人员表单，包括分工和验收部位
          if (statusCode !== 0) {
            for (let index in this.$refs.preAcceptanceTeam) {
              let item = this.$refs.preAcceptanceTeam[index]
              item.validate((res) => {
                // 校验到最后一个验收人员表单
                if (!res) {
                  result = false
                }
              })
            }
          }
          if (result) {
            // 提交表单
            let form = this.$clone(this.form)
            // 校验质量验收计划
            if (!form.detailsId) {
              this.$message.warning('请选择质量验收计划！')
              return
            }
            form.statusCode = this.statusCode == '3' && statusCode == 0 ? this.statusCode : statusCode
            this.loading[statusCode] = true
            this.submitApprovalConfirm(statusCode == 1?this.processConfig: 6, (flag)=>{
              if(!flag) {
                this.loading[statusCode] = false
                return
              }
              application[name](form)
                      .then((res) => {
                        this.loading[statusCode] = false
                        this.$message.success(['保存', '提交'][statusCode] + '成功！')
                        if(statusCode*1===1) {
                          //提交时，返回id
                          this.businessId = res.data.id;
                          this.setProcessConfig = this.processConfig;
                          return
                        }else{
                          this.$multiTab.close()
                        }
                      })
                      .catch((res) => {
                        // this.$message.warning(res.data?.message || ['保存', '提交'][statusCode] + '失败！')
                        this.loading[statusCode] = false
                      })
            })

          }
        } else {
          this.$message.warning('数据填写不完整，不能提交')
        }
      })
    },
  },
}
</script>
<style lang="less" scoped>
.text_name {
  margin-top: -3px;
  word-wrap: break-word;
}
/deep/ .ant-form-item .ant-form-item-label{
    width: 160px;
}
/deep/ .ant-form-item .ant-form-item-control-wrapper{
    width: calc(100% - 160px);
}
</style>
